package com.qc31.monitorlib.ui.carmonitor

import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import autodispose2.autoDispose
import com.qc31.baselib.auto.AutoDisposeViewModel
import com.qc31.baselib.net.AppContext
import com.qc31.baselib.utils.GsonUtil
import com.qc31.baselib.utils.MLog
import com.qc31.comlib.UrlUtil
import com.qc31.comlib.entity.RealVideoInfo
import com.qc31.comlib.entity.VideosPass
import com.qc31.comlib.net.ServiceHelper
import com.qc31.monitorlib.R

/** @Author Jasper @Time 2020/9/12 @Desc 实时视频 */
class CarRealVideoViewModel : AutoDisposeViewModel() {
    var videos = ""
    var carId: String = ""
    var audioPass: String? = ""
    val mVideoEntitys = ArrayList<RealVideoInfo>()

    /** 处理视频通道 */
    fun handleVideos(): ArrayList<RealVideoInfo>? {
        audioPass = ""
        if (TextUtils.isEmpty(videos)) return null
        mVideoEntitys.clear()

        if (videos.length > 3) {
            val entity = GsonUtil.formObject<VideosPass>(videos)
            val passEntitys = entity.vs.split(",")
            for (pass in passEntitys) {
                val passInfos = pass.split(":");
                val passNum = passInfos[0]
                if (passInfos[1].isNotEmpty()) {
                    mVideoEntitys.add(
                        RealVideoInfo(videoPass = passNum, videoName = passInfos[1])
                    )
                } else {
                    mVideoEntitys.add(
                        RealVideoInfo(
                            videoPass = passNum,
                            videoName = "${AppContext.getDescById(R.string.desc_video_pass)} $passNum"
                        )
                    )
                }
            }

            if (mVideoEntitys.size > 0) audioPass = mVideoEntitys[0].videoPass

            return mVideoEntitys
        }
        return null
    }

    /** 关闭视频 */
    fun closeVideo(
        uuid: String,
    ) {
        val url = "httpflv.rctr.close.$uuid"
        ServiceHelper.getRepository().getVideoState(url).autoDispose(this).subscribe({}, {
            MLog.e("测试============${it.message}")
        })
    }

    /**
     * 关闭对讲
     *
     * @param uuid
     */
    fun closeAudio(
        uuid: String
    ) {
        val url = "/httpflv.state.$uuid"
        ServiceHelper.getRepository().getState(url).autoDispose(this)
            .subscribe({
                val toast = UrlUtil.getToastMap()[it]
                MLog.e("结果========= $toast")
            }, {
                MLog.e("结果===失败===== $it")
            })
    }

    //云台控制
    var speed = 127
    var channel = ""


    /** drct：1上移 2下移 3左移 4右移 0停止 speed：旋转速度0-255,默认127 */
    private fun controlCloud(drct: Int): String {
        return "phone.cloud_ctr.0.$carId.$channel.$drct.$speed"
    }

    /**
     * 1.调整焦距(0焦距变小 1焦距变大) 2.调整光圈(0光圈放大 1光圈缩小) 3.调整雨刷(0雨刷关闭 1雨刷打开)
     * 4.调整补光(0补光关闭 1补光打开) 5.调整变倍(0变倍调大 1变倍调小)
     */
    fun getParams(type: Int, action: Int) =
        "phone.cloud_ctr.$type.$carId.$channel.$action"

    /**
     * 判断参数是否合格
     *
     * @return
     */
    fun isParamsOk(): Boolean {
        if (carId.isEmpty()) {
            toast(R.string.hint_toast_choose_car)
            return true
        }
        if (channel.isEmpty()) {
            toast(R.string.hint_toast_choose_channel)
            return true
        }
        return false
    }

    //云台控制
    fun control(drct: Int) {
        toastLoading(true)
        if (isParamsOk()) return
        ServiceHelper.getRepository().getVideoState(controlCloud(drct))
            .autoDispose(this).subscribe({
                if (it == "1") {
                    toastLoading(false)
                    toast(R.string.toast_set_success)
                    return@subscribe
                }
            }, error)
    }

    /**
     * 1.调整焦距(0焦距变小 1焦距变大) 2.调整光圈(0光圈放大 1光圈缩小) 3.调整雨刷(0雨刷关闭 1雨刷打开)
     * 4.调整补光(0补光关闭 1补光打开) 5.调整变倍(0变倍调大 1变倍调小)
     *
     * @param type
     * @param action
     */
    fun changeAction(type: Int, action: Int) {
        MLog.e("设置======$type    $action")
        toastLoading(true)
        if (isParamsOk()) return
        ServiceHelper.getRepository().getVideoState(getParams(type, action))
            .autoDispose(this).subscribe({
                if (it == "1") {
                    if (type == 3) setWiper(action)
                    else if (type == 4) setLight(action)
                    toastLoading(false)
                    toast(R.string.toast_set_success)
                    return@subscribe
                }
            }, error)
    }

    private fun setLight(light: Int) {
        val action = getAction()
        putAction(light, action.wiper)
    }

    private fun setWiper(wiper: Int) {
        val action = getAction()
        putAction(action.light, wiper)
    }

    data class ActionData(var light: Int = 0, var wiper: Int = 0)

    private val actionMap = HashMap<String, ActionData>()

    private fun putAction(light: Int, wiper: Int) {
        val actionData = actionMap[channel]
        if (actionData == null) {
            actionMap[channel] = ActionData(light, wiper)
        } else {
            actionData.light = light
            actionData.wiper = wiper
        }
        actionLive.postValue(true)
    }

    fun getAction(): ActionData {
        return actionMap[channel] ?: ActionData()
    }

    var actionLive = MutableLiveData<Boolean>()

    fun clearMap() {
        actionMap.clear()
    }
}
